from common.utils.rights import permission_required, view_logging_required
from common.utils.file_read import file_read
from . import index_bp
from flask import render_template,request
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import cv2
import numpy as np


def lowdpi(picData,dpi):
    # 获取图像高度和宽度
    height = picData.shape[0]
    width = picData.shape[1]

    # 采样转换成dpi*dpi区域
    numHeight = int(height / dpi)
    numWidth = int(width / dpi)

    # 创建一幅图像
    new_img = np.zeros((height, width, 3), np.uint8)

    # 图像循环采样dpi*dpi区域
    for i in range(dpi):
        # 获取Y坐标
        y = i * numHeight
        for j in range(dpi):
            # 获取X坐标
            x = j * numWidth
            # 获取填充颜色 左上角像素点
            b = picData[y, x][0]
            g = picData[y, x][1]
            r = picData[y, x][2]

            # 循环设置小区域采样
            for n in range(numHeight):
                for m in range(numWidth):
                    new_img[y + n, x + m][0] = np.uint8(b)
                    new_img[y + n, x + m][1] = np.uint8(g)
                    new_img[y + n, x + m][2] = np.uint8(r)
    return new_img


@index_bp.get('/dpi_pro')
@index_bp.post('/dpi_pro')
@view_logging_required
@permission_required("dpi:pro")
def dpi_pro():
    #读取文件
    if request.method == "GET":
        return render_template('admin/cv/dpi.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']
            dpi = int(request.form.get('number'))
            file_url = file_read(f)
            picData = cv2.imread(file_url)
            res_pic = 'static/download/dpi.jpg'
            res = lowdpi(picData,dpi)
            cv2.imwrite(res_pic, res)
            return render_template('admin/cv/dpi.html',res_pic=res_pic,pic=file_url)
